import { nextTick, onUnmounted, Ref, ref } from 'vue';

export const useScrollTable = (contentRef: Ref, list: Ref) => {
  const containerSideRef = ref<HTMLDivElement>();
  const scrollData: any = {
    rowHeight: 32,
    contentHeight: 0,
    totalHeight: 0,
    totalPage: 0,
    perPageHeight: 0,
    currentPage: 1,
    timer: null,
  };

  const initData = async () => {
    await nextTick();
    const contentTableDom = contentRef.value?.querySelector('.content');
    const boundingClientRect = contentTableDom.getBoundingClientRect();
    scrollData.totalHeight = scrollData.rowHeight * list.value.length;
    scrollData.contentHeight = boundingClientRect.height;
    scrollData.perPageHeight = Math.floor(scrollData.contentHeight / scrollData.rowHeight) * scrollData.rowHeight;
    scrollData.totalPage = Math.ceil(scrollData.totalHeight / scrollData.perPageHeight);
    containerSideRef.value.addEventListener('mouseover', handleMouseover);
    containerSideRef.value.addEventListener('mouseout', handleMouseout);

    setTimer();
  };

  const handleMouseover = () => {
    clearInterval(scrollData.timer);
    scrollData.timer = null;
  };

  const handleMouseout = () => {
    setTimer();
  };

  const setTimer = () => {
    scrollData.timer = setInterval(() => {
      const contentTableDom = contentRef.value?.querySelector('.content');
      if (contentTableDom.scrollTop >= scrollData.totalHeight - scrollData.contentHeight) {
        contentTableDom.scrollTop = 0;
        return;
      }

      contentTableDom.scrollTop += scrollData.perPageHeight;
    }, 3000);
  };

  onUnmounted(() => {
    clearInterval(scrollData.timer);
    scrollData.timer = null;
  });

  return { containerSideRef, scrollData, initData };
};
